import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import prisma from '@/app/lib/prisma';
import { verifyToken } from '@/app/lib/auth';

export async function GET() {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('auth-token')?.value;

    if (!token) {
      return NextResponse.json(
        { message: '请先登录后再使用此功能' },
        { status: 401 }
      );
    }

    const payload = verifyToken(token);
    if (!payload) {
      return NextResponse.json(
        { message: '登录已过期，请重新登录' },
        { status: 401 }
      );
    }

    // 获取最近7天的记录
    const records = await prisma.dietRecord.findMany({
      where: {
        userId: payload.userId,
        mealTime: {
          gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // 7天前
        },
      },
      orderBy: {
        mealTime: 'desc',
      },
      take: 20, // 最多显示20条记录
    });

    return NextResponse.json({ records });
  } catch (error) {
    console.error('获取饮食记录错误:', error);
    return NextResponse.json(
      { message: '获取饮食记录失败' },
      { status: 500 }
    );
  }
} 